//
//  USAlbumPhotoListController.m
//  us
//
//  Created by karry on 2025/4/11.
//

#import "USAlbumPhotoListController.h"
#import "USPhotoCell.h"
#import "USPhotoSectionHeader.h"
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
#import "USPhotoUploadTool.h"
#import "USMediaPickerManager.h"
#import "USUploadPhotoController.h"
#import "USPhotoPreviewController.h"
#import "USPhotoModel.h"
#import "USMediaUploadManager.h"

#import <MJRefresh/MJRefresh.h>
@interface USAlbumPhotoListController ()<UICollectionViewDelegate,UICollectionViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic,strong)UICollectionView *collectionView;
@property (nonatomic,assign) BOOL isEditingMode;
@property (nonatomic,strong) UIButton *deleteBtn;
@property (nonatomic,strong) UIBarButtonItem *addItem;
@property (nonatomic,strong) UIBarButtonItem *editItem;

@property (nonatomic,strong) NSMutableArray <NSArray<USPhotoModel *> *>*list;
@property (nonatomic,assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) BOOL hasMore;


@end

@implementation USAlbumPhotoListController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    self.title = self.album.albumName;
    
    [self setupView];
    [self loadData];

    if (!self.album) {
        //其他资方直接跳转详情
        [self getAlbumInfoID:self.albumId success:^{
                    
        }];
    }
}

- (void)setupView{
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    
    CGFloat space = 16;
    CGFloat margin = 8;
    NSInteger count = 3;
    CGFloat w = (self.view.frame.size.width - margin * (count - 1) - space * 2)/count;
    layout.itemSize = CGSizeMake(floorf(w), floorf(w));
    layout.sectionInset = UIEdgeInsetsMake(0, 16, 16, 16);
    layout.minimumLineSpacing = margin;
    layout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 40);
    layout.minimumInteritemSpacing = margin;
    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
    _collectionView = collectionView;
    collectionView.dataSource = self;
    collectionView.delegate = self;
    collectionView.backgroundColor = UIColor.clearColor;
    collectionView.emptyDataSetSource = self;
    collectionView.allowsMultipleSelectionDuringEditing = YES;

    [collectionView registerClass:[USPhotoCell class] forCellWithReuseIdentifier:@"USPhotoCellId"];
    [collectionView registerClass:[USPhotoSectionHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"USPhotoSectionHeaderId"];
    [self.view addSubview:collectionView];
    [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop);
        make.bottom.mas_offset(0);
    }];
    
    
    self.addItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"ic_add"] style:UIBarButtonItemStylePlain target:self action:@selector(addAction:)];
    self.editItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"icon_edit"] style:UIBarButtonItemStylePlain target:self action:@selector(editAction:)];

    
    UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"ic_close"] style:UIBarButtonItemStylePlain target:self action:@selector(cancelEditAction)];
    

    UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.deleteBtn = deleteBtn;
    [deleteBtn setTitle:@" 删除(0) " forState:0];
    [deleteBtn setTitleColor:UIColor.labelColor forState:0];
    [deleteBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [deleteBtn addTarget:self action:@selector(deleteAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *deleteItem = [[UIBarButtonItem alloc] initWithCustomView:deleteBtn];
 
    self.navigationItem.rightBarButtonItems = @[self.addItem,self.editItem];
    
    @weakify(self);
    [RACObserve(self, isEditingMode) subscribeNext:^(NSNumber *editing) {
        @strongify(self);
        BOOL isEditing = editing.boolValue;

        if (isEditing) {
            self.navigationItem.leftBarButtonItem = cancelItem;
            self.navigationItem.rightBarButtonItems = @[deleteItem];

            self.collectionView.allowsMultipleSelection = YES;
        } else {
            self.navigationItem.leftBarButtonItem = nil;
            self.navigationItem.rightBarButtonItems = @[self.addItem,self.editItem];

        }

     }];
    
}

 

- (void)loadData{
    [super loadData];
 
    [self setupRefresh];
    
    [self.collectionView.mj_header beginRefreshing];

}
- (void)setupRefresh {
    
   self.currentPage = 1;
   self.pageSize = 15;

   @weakify(self)
    
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self)
        self.currentPage = 1;
        [self updatePhotoList];
    }];
    
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        @strongify(self)
        
        if (self.albumId.length == 0) {
            [self.collectionView.mj_footer endRefreshing];
            return;
        }
        
        if (self.hasMore) {
            self.currentPage += 1;
            [self updatePhotoList];
        } else {
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
        }
    }];
}
- (void)updatePhotoList{
    if (self.albumId.length == 0) {
        return;
    }
    NSDictionary *params = @{ @"albumId" : self.albumId ?:@"",
                              @"current": @(self.currentPage),
                              @"size": @(self.pageSize)
    };

    [[EMNetWork shareManager] em_post:API_AlbumPhotoList
                               params:params
                                  hud:nil
                            showError:YES
                              success:^(EMApiModel *api) {
        
        if (!api.success) {
            [self loadingFailed];
            return;
        }
        [self.deleteBtn setTitle:@"删除(0)" forState:0];

        if (self.currentPage == 1) {

            [self.list removeAllObjects];
        }
        
        NSArray *photoList = [USPhotoModel mj_objectArrayWithKeyValuesArray:api.data[@"photoList"][@"records"]];
        
        // 是否还有更多
        self.hasMore = photoList.count == self.pageSize;
        
        NSLog(@"self.hasMore = %@",self.hasMore?@"还有更多":@"没有数据了");
        // 结束刷新状态
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        
        if (!self.hasMore) {
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.collectionView.mj_footer resetNoMoreData];
        }
        
        [self addPhotoModels:photoList isNewAdd:NO];
        
       
    } fail:^{
        
 
    }];
    
    
}
  
// 添加新数据并自动按日期归组合并
- (void)addPhotoModels:(NSArray<USPhotoModel *> *)newPhotos isNewAdd:(BOOL)isNewAdd{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    
    // 暂存每条新数据的日期字符串
    for (USPhotoModel *photo in newPhotos) {
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:photo.recordDate];
        NSString *dateKey = [formatter stringFromDate:date];
        
        BOOL inserted = NO;
        
        // 遍历已有分组，看是否已存在对应日期
        for (NSMutableArray<USPhotoModel *> *group in self.list) {
            USPhotoModel *firstInGroup = group.firstObject;
            NSString *groupKey = [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:firstInGroup.recordDate]];
            
            if ([groupKey isEqualToString:dateKey]) {
                if (isNewAdd) {
                    [group insertObject:photo atIndex:0];
                }else{
                    [group addObject:photo];
                }
                inserted = YES;
                break;
            }
        }
        
        // 若没有对应日期分组，则新建一个
        if (!inserted) {
            NSMutableArray *newGroup = [NSMutableArray arrayWithObject:photo];
            [self.list addObject:newGroup];
        }
    }
    
    // 排序所有分组：按每组的第一条记录的时间降序
    [self.list sortUsingComparator:^NSComparisonResult(NSArray<USPhotoModel *> *group1, NSArray<USPhotoModel *> *group2) {
        NSTimeInterval t1 = group1.firstObject.recordDate;
        NSTimeInterval t2 = group2.firstObject.recordDate;
        return t1 < t2 ? NSOrderedDescending : NSOrderedAscending;
    }];
    
    if (self.list.count == 0) {
        self.dataState = EmptyDataStateNoData;
    }
    self.collectionView.mj_footer.hidden = self.list.count == 0;

    [self.collectionView reloadData];
    [self.collectionView reloadEmptyDataSet];
}

 - (NSMutableArray <NSArray<USPhotoModel *> *>*)list {
    if (_list == nil) {
        _list = [NSMutableArray array];
    }
    return _list;
}

- (void)PaySuccess {
    [USFeedbackTool impactSoft];


}

- (void)addAction:(UIBarButtonItem *)sender{
    
    @weakify(self)
    DTItem *item0 = [DTItem itemWithTitle:@"拍摄" image:[UIImage imageNamed:@"icon-camera-22"] tag:0 identifier:nil handle:^(DTItem *item) {
        @strongify(self)
        [self takePhotoAction];
    }];
    
    DTItem *item1 = [DTItem itemWithTitle:@"相册" image:[UIImage imageNamed:@"icon-photo-22"] tag:0 identifier:nil handle:^(DTItem *item) {
        @strongify(self)
        [self presentImagePicker];
    }];

    DTTargetView *view = [DTTargetView initWithBarItem:sender item:@[item0,item1]];
    
    [view show];
    
}
- (void)editAction:(UIBarButtonItem *)sender{
    [USFeedbackTool impactSoft];

    [self.collectionView setEditing:YES];
    self.isEditingMode = YES;
    [self.collectionView reloadData];
}
- (void)cancelEditAction {
    [USFeedbackTool impactSoft];

    [self.collectionView setEditing:NO];
    self.isEditingMode = NO;
    [self.collectionView reloadData];

}
- (void)deleteAction {
    if (self.filesForSelectedItems.count == 0) {
        return;
    }
    MOAlertBaseView *alert = [[MOAlertBaseView alloc]initWithTitle:@"确定删除选中的照片吗" detailTitle:@"此操作不可撤销哦，请谨慎操作" contentView:nil leftButtonImageName:nil rightButtonImageName:nil autoDissmiss:YES tapDissmiss:YES];
    alert.titleLabel.textColor = UIColor.us_redColor;
    @weakify(self)
    alert.didClickIndexBlock = ^(NSInteger index) {
        @strongify(self)
        if (index == 1) {
            [self requestDeletePhotos];
        }
    };
    
    [alert show];

    
}

#pragma mark - net
- (void)getAlbumInfoID:(NSString *)albumId success:(void(^)(void))success {
    [[EMNetWork shareManager] em_post:API_SharedAlbumInfo
                               params:@{@"albumId":albumId?:@""}
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
        
        if (!api.success) {
            return;
        }
        
        if (api.data[@"Album"]) {
            self.title = api.data[@"Album"][@"albumName"];
            self.albumFirstDirectory = api.data[@"Album"][@"albumFirstDirectory"];
            self.albumSecondDirectory = api.data[@"Album"][@"albumSecondDirectory"];

        }
     
        success();
    } fail:^{
        
        
    }];
}
- (void)requestDeletePhotos {
 
    NSMutableArray *photoIdList = [NSMutableArray array];
    for (USPhotoModel *model in self.filesForSelectedItems) {
        [photoIdList addObject:model.photoId?:@""];
    }
    
    if (photoIdList.count == 0) {
        
        return;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"albumId"] = self.albumId;
    params[@"photoIdList"] = photoIdList;

    [[EMNetWork shareManager] em_post:API_AlbumDeletePhotos
                               params:params
                                  hud:nil
                            showError:YES
                              success:^(EMApiModel *api) {

        if (!api.success) {
            return;
        }
        
        [self deleteLocalDataIndexPaths:self.collectionView.indexPathsForSelectedItems];
  
    } fail:^{


    }];
}
- (void)takePhotoAction{
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.delegate = self;
        picker.videoMaximumDuration = 60;
        picker.allowsEditing = NO; // 是否允许编辑
        picker.showsCameraControls = YES;
        picker.mediaTypes = @[UTTypeImage.identifier, UTTypeMovie.identifier];
        [self presentViewController:picker animated:YES completion:nil];
    } else {
        [self.view us_makeAlert:@"当前设备不支持拍照" subTitle:nil];
    }
    
}

//相册过来的要进下一页调整
- (void)prepareUpdateMedias:(NSArray *)medias{
    
    if (medias.count == 0) {
        return;
    }
    
    USUploadPhotoController *vc = [USUploadPhotoController new];
    [vc.mediaList addObjectsFromArray:medias];
    vc.albumId = self.albumId;
    vc.albumFirstDirectory = self.albumFirstDirectory;
    vc.albumSecondDirectory = self.albumSecondDirectory;
    @weakify(self)
    vc.uploadSuccessPhotos = ^(NSArray<USPhotoModel *> * _Nonnull photoModels) {
     @strongify(self)
        [self addPhotoModels:photoModels isNewAdd:YES];
    };
    [self.navigationController pushViewController:vc animated:YES];
    
    
}

//直接上传
- (void)updateImageWithMedias:(NSArray <USMediaResult *>*)medias{
    [USMediaUploadManager uploadImages:medias albumFirstDirectory:self.albumFirstDirectory albumSecondDirectory:self.albumSecondDirectory progress:^(NSInteger current, NSInteger total) {
    } success:^(NSArray<USPhotoModel *> *models) {
        
        [self uploadPhotos:models];
    } failure:^(NSError *error) {
        
    }];
}

- (void)uploadPhotos:(NSArray <USPhotoModel *>*)photos{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"albumId"] = self.albumId?:@"";
    
    NSMutableArray *list = [NSMutableArray array];
    for (USPhotoModel *model in photos) {
        [list addObject:@{
            @"cosUrl":model.cosUrl?:@"",
            @"type":@(model.type),
            @"photoFirstDirectory" :model.photoFirstDirectory?:@"",
            @"photoSecondDirectory":model.photoSecondDirectory?:@"",
            @"recordDate": @(model.recordDate),
            @"fileName":model.fileName?:@"",
            @"liveMovUrl":model.liveMovUrl?:@"",
            @"liveMoveFileName":model.liveMoveFileName?:@"",
            @"size":@(model.size),
            @"liveMovSize":@(model.liveMovSize)
        }];
    }
    
    params[@"photoList"] = list;
    
    @weakify(self)
    [[EMNetWork shareManager] em_post:API_AlbumAddPhotos
                               params:params
                                  hud:nil
                            showError:YES
                              success:^(EMApiModel *api) {
        @strongify(self)
        if (api.success) {
            [self addPhotoModels:photos isNewAdd:YES];
        }
    } fail:^{
        
    }];
}


- (void)presentImagePicker{
    [USFeedbackTool impactSoft];
    [self startUpload];

    @weakify(self)
    [USMediaPickerManager presentPickerFrom:self type:USPickerMediaType_Image_Video limit:20 didFinishPicking:^{

    } progressHandler:^(NSInteger current, NSInteger total) {
   
        @strongify(self)
        
        NSLog(@"%ld",current);
        
    } completion:^(NSArray<USMediaResult *> * _Nonnull results) {
        @strongify(self)
        [self endUpLoad];

        [self prepareUpdateMedias:results];
        
    }];
    
}
- (void)startUpload{
    [self.indicator startAnimating];
    UIBarButtonItem *loadingItem = [[UIBarButtonItem alloc] initWithCustomView:self.indicator];
    self.editItem.enabled = NO;
    self.navigationItem.rightBarButtonItems = @[loadingItem,self.editItem];
    self.view.userInteractionEnabled = NO;
    
}
- (void)endUpLoad{
    self.editItem.enabled = YES;
    self.navigationItem.rightBarButtonItems = @[self.addItem,self.editItem];
    [self.indicator stopAnimating];
    self.view.userInteractionEnabled = YES;
}


#pragma mark - UIImagePickerControllerDelegate,UINavigationControllerDelegate;

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {

    NSString *mediaType = info[UIImagePickerControllerMediaType];

    if ([mediaType isEqualToString:UTTypeImage.identifier]) {
        // 图片
        UIImage *image = info[UIImagePickerControllerOriginalImage];
        NSData *imageData = UIImageJPEGRepresentation(image, 1);
        NSString *tmpPath = [USPhotoUploadTool imagePathWithUUID:NSUUID.UUID.UUIDString];
        [imageData writeToFile:tmpPath atomically:YES];
        
        
        USMediaResult *item = [[USMediaResult alloc] init];
        item.uuid = [[NSUUID UUID] UUIDString];
        item.filePath = tmpPath;
        item.type = USMediaTypeImage;
        item.recordDate = (NSInteger)[[NSDate date] timeIntervalSince1970];
        item.customDate = (NSInteger)[[NSDate date] timeIntervalSince1970];
        
        
        [self updateImageWithMedias:@[item]];
     
    } else if ([mediaType isEqualToString:UTTypeMovie.identifier]) {
        
        // 视频
        NSURL *videoURL = info[UIImagePickerControllerMediaURL];
        NSString *path = [USPhotoUploadTool videoPathWithUUID:NSUUID.UUID.UUIDString];
        NSURL *tmpURL = [NSURL fileURLWithPath:path];
        NSError *error = nil;
        [[NSFileManager defaultManager] copyItemAtURL:videoURL toURL:tmpURL error:&error];
        if (error) {
            [self.view makeToast:error.localizedDescription];
            return;
        }
        
        USMediaResult *item = [[USMediaResult alloc] init];
        item.uuid = [[NSUUID UUID] UUIDString];
        item.filePath = path;
        item.type = USMediaTypeVideo;
        item.recordDate = (NSInteger)[[NSDate date] timeIntervalSince1970];
        item.customDate = (NSInteger)[[NSDate date] timeIntervalSince1970];
        
        [self updateImageWithMedias:@[item]];
    }

    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)deleteLocalDataIndexPaths:(NSArray<NSIndexPath *> *)deleteIndexPaths{
    // 用于保存更新后的数据
    NSMutableArray *newList = [NSMutableArray arrayWithCapacity:self.list.count];

    // 先复制原数据
    for (NSArray *sectionItems in self.list) {
        [newList addObject:[sectionItems mutableCopy]];
    }
 
    // 倒序排序选中项，避免索引错乱
    NSArray<NSIndexPath *> *sortedIndexPaths = [deleteIndexPaths sortedArrayUsingComparator:^NSComparisonResult(NSIndexPath *obj1, NSIndexPath *obj2) {
        if (obj1.section == obj2.section) {
            return obj2.row - obj1.row;
        }
        return obj2.section - obj1.section;
    }];

    // 删除数据
    for (NSIndexPath *indexPath in sortedIndexPaths) {
        NSMutableArray *sectionArray = newList[indexPath.section];
        if (indexPath.item < sectionArray.count) {
            [sectionArray removeObjectAtIndex:indexPath.item];
        }
    }
    
    
    // 删除空 section
    NSMutableIndexSet *emptySections = [NSMutableIndexSet indexSet];
    for (NSInteger i = 0; i < newList.count; i++) {
        if ([newList[i] count] == 0) {
            [emptySections addIndex:i];
        }
    }
    [newList removeObjectsAtIndexes:emptySections];

    // 替换数据源
    self.list = newList;

    if (self.list.count == 0) {
        self.dataState = EmptyDataStateNoData;
    }
    self.collectionView.mj_footer.hidden = self.list.count == 0;
    
    [self.collectionView performBatchUpdates:^{
        [self.collectionView deleteItemsAtIndexPaths:deleteIndexPaths];
        
        if (emptySections.count > 0) {
            [self.collectionView deleteSections:emptySections];
        }
    } completion:^(BOOL finished) {
        [self.deleteBtn setTitle:@"删除(0)" forState:0];
        [self.collectionView setEditing:NO];
        self.isEditingMode = NO;
        [self.collectionView reloadData];

    }];


    if ( self.list.count == 0 && self.hasMore) {
        [self.collectionView.mj_header beginRefreshing];
    }
    
}

//当前选中的文件
- (NSArray <USPhotoModel *>*)filesForSelectedItems{
    
    NSMutableArray *arr = [NSMutableArray array];

    [self.collectionView.indexPathsForSelectedItems enumerateObjectsUsingBlock:^(NSIndexPath * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        USPhotoModel *model = self.list[obj.section][obj.row];
        [arr addObject:model];
    }];
    
    return arr;
    
}
//section已经选中的row
- (NSInteger)selectedItemCountInSection:(NSInteger)section {
    NSArray<NSIndexPath *> *selectedIndexPaths = [self.collectionView indexPathsForSelectedItems];
    
    NSInteger count = 0;
    for (NSIndexPath *indexPath in selectedIndexPaths) {
        if (indexPath.section == section) {
            count++;
        }
    }
    return count;
}
- (void)reloadHeaderAtIndexPath:(NSIndexPath *)indexPath {
    
    [self.deleteBtn setTitle:[NSString stringWithFormat:@"删除(%li)",self.collectionView.indexPathsForSelectedItems.count] forState:0];
    
    USPhotoSectionHeader *header = (USPhotoSectionHeader *)[self.collectionView supplementaryViewForElementKind:UICollectionElementKindSectionHeader atIndexPath:[NSIndexPath indexPathForItem:0 inSection:indexPath.section]];
    
    NSInteger row = [self.collectionView numberOfItemsInSection:indexPath.section];
    NSInteger count = [self selectedItemCountInSection:indexPath.section];
    if (row == count) {
        [header.chooseBtn setTitle:@"取消全选" forState:UIControlStateNormal];
    }else{
        [header.chooseBtn setTitle:@"全选" forState:UIControlStateNormal];
    }
    
}
#pragma mark - <UICollectionViewDelegate,UICollectionViewDataSource>
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (collectionView.isEditing) {

        [self reloadHeaderAtIndexPath:indexPath];
    }else{

        NSMutableArray *mediaList = [NSMutableArray array];
        
        __block NSInteger calculatedIndex = 0;
        [self.list enumerateObjectsUsingBlock:^(NSArray<USPhotoModel *> * _Nonnull group, NSUInteger idx, BOOL * _Nonnull stop) {
            if (idx < indexPath.section) {
                calculatedIndex += group.count;
            } else if (idx == indexPath.section) {
                calculatedIndex += indexPath.row;
            }
            [mediaList addObjectsFromArray:group];
        }];
        
        USPhotoPreviewController *vc = [[USPhotoPreviewController alloc] init];
        vc.albumId = self.albumId?:@"";
        vc.showBotTool = YES;
        vc.items = mediaList;
        vc.currentIndex = calculatedIndex;
        [self.navigationController presentViewController:vc animated:YES completion:nil];

        @weakify(self)
        vc.deletePhotoBlock = ^(USPhotoModel * _Nonnull photoModel) {
            @strongify(self)

            for (NSInteger section = 0; section < self.list.count; section++) {
                for (int item = 0; item < self.list[section].count; item++) {
                    if (self.list[section][item] == photoModel) {
                        
                        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:item inSection:section];
                        [self deleteLocalDataIndexPaths:@[indexPath]];
                        break;
                    }
                }
            }
        };

    }


}
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView.isEditing) {
        [self reloadHeaderAtIndexPath:indexPath];

    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath {
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        USPhotoSectionHeader *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"USPhotoSectionHeaderId" forIndexPath:indexPath];
        
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:self.list[indexPath.section].firstObject.recordDate];
        header.titleLabel.attributedText = [self attributedStringForDate:date]; // 示例日期
        
        header.edit = collectionView.isEditing;

        NSInteger row = [self.collectionView numberOfItemsInSection:indexPath.section];
        NSInteger count = [self selectedItemCountInSection:indexPath.section];
        if (row == count) {
            [header.chooseBtn setTitle:@"取消全选" forState:UIControlStateNormal];
        }else{
            [header.chooseBtn setTitle:@"全选" forState:UIControlStateNormal];
        }
        
        @weakify(self)
        @weakify(header)
        header.chooseBlock = ^{
            @strongify(self)
            @strongify(header)
            NSInteger row = [collectionView numberOfItemsInSection:indexPath.section];
            NSInteger count = [self selectedItemCountInSection:indexPath.section];//已经选中的
      
            for (NSInteger i = 0; i < row; i++) {
                NSIndexPath *itemIndexPath = [NSIndexPath indexPathForRow:i inSection:indexPath.section];
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (row == count) {
                        [self.collectionView deselectItemAtIndexPath:itemIndexPath animated:NO];
                        [header.chooseBtn setTitle:@"全选" forState:0];
                    }else{
                        [self.collectionView selectItemAtIndexPath:itemIndexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
                        [header.chooseBtn setTitle:@"取消全选" forState:0];
                    }
                    
                    [self.deleteBtn setTitle:[NSString stringWithFormat:@"删除(%li)",self.collectionView.indexPathsForSelectedItems.count] forState:0];
                });

            }
        };
        return header;
    }
    return [UICollectionReusableView new];
}
- (NSAttributedString *)attributedStringForDate:(NSDate *)date {
    NSDateFormatter *dayFormatter = [[NSDateFormatter alloc] init];
    dayFormatter.dateFormat = @"d"; // 日
    NSString *dayString = [dayFormatter stringFromDate:date];

    NSDateFormatter *monthFormatter = [[NSDateFormatter alloc] init];
    monthFormatter.dateFormat = @"M月"; // 月
    NSString *monthString = [monthFormatter stringFromDate:date];

    NSDateFormatter *yearFormatter = [[NSDateFormatter alloc] init];
    yearFormatter.dateFormat = @"yyyy"; // 年
    NSString *yearString = [yearFormatter stringFromDate:date];

    NSString *fullString = [NSString stringWithFormat:@"%@ ,%@ %@", dayString,monthString,yearString];

    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:fullString];

    // 先设置整体样式（基础字体 + 颜色）
    [attr addAttributes:@{
        NSFontAttributeName: [UIFont systemFontOfSize:14 weight:UIFontWeightLight],
        NSForegroundColorAttributeName: UIColor.labelColor
    } range:NSMakeRange(0, fullString.length)];

    // 再设置“日”部分（加粗、加大、彩色）
    NSRange dayRange = [fullString rangeOfString:dayString];
    if (dayRange.location != NSNotFound) {
        [attr addAttributes:@{
            NSFontAttributeName: [UIFont systemFontOfSize:20 weight:UIFontWeightSemibold],
            NSForegroundColorAttributeName: UIColor.us_redColor
        } range:dayRange];
    }

    return attr;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.list.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    NSArray *arr = [self.list objectAtIndex:section];
    return arr.count;
    
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    USPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"USPhotoCellId" forIndexPath:indexPath];
    
    USPhotoModel *model = self.list[indexPath.section][indexPath.row];
    
    cell.photoModel = model;
    
    cell.edit = collectionView.isEditing;
    
    return cell;
    
}

#pragma mark - DZNEmptyDataSetSource,DZNEmptyDataSetDelegate


- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView{
    
//    if (self.dataState == EmptyDataStateLoading) {
//        UIView *contentView = [UIView new];
//        contentView.frame = CGRectMake(0, 0, self.view.jk_width, 200);
//        
//        NSString *gifPath = [[NSBundle mainBundle] pathForResource:@"load_page" ofType:@"gif"];
//        UIImageView *imageView = [[UIImageView alloc] initWithImage:nil];
//        imageView.contentMode = UIViewContentModeScaleAspectFit;
//        imageView.frame = CGRectMake(0, 0, 200, 200);
//        [imageView sd_setImageWithURL:[NSURL fileURLWithPath:gifPath]];
//        
//        [contentView addSubview:imageView];
//        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.width.height.mas_equalTo(200);
//            make.center.mas_equalTo(contentView);
//        }];
//        
//        return contentView;
//    }
    if (self.dataState == EmptyDataStateNoData) {
        USEmptyView *emptyView = [[USEmptyView alloc] initWithFrame:CGRectMake(0, 0, self.view.jk_width, 0)];
        emptyView.image = [UIImage imageNamed:@"Frame 112"];
        emptyView.title = @"还没有照片哦\n快来添加吧！";
        emptyView.btnTitle = @"添加照片";
        emptyView.userInteractionEnabled = YES;
        [emptyView.btn addTarget:self action:@selector(presentImagePicker) forControlEvents:UIControlEventTouchUpInside];
        return emptyView;
    }
   
    return nil;
    
}

- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView {
    
    
    return YES; // 允许点击
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    
    
    return YES; // 避免 scrollView 吃掉 touch 事件
}



@end
